/*************************************************************************
	> File Name: conf.cpp
	> Author: gyl
	> Mail: gyldeyx@qq.com
	> Created Time: Thu 21 Jan 2021 06:39:35 PM CST
 ************************************************************************/

#include "conf.h"
#include <stdio.h>
#include <string.h>

Config::Config(const char *pConfigFileName)
    : m_pFp(nullptr) {

    strConfigFileName.append(pConfigFileName);

    openConfigFile();
    readConfigFile();
}

Config::~Config() {
    closeConfigFile();
}

void Config::openConfigFile() {
    if ((m_pFp = fopen(strConfigFileName.c_str(), "r")) == NULL) {
        perror("fopen()");
        return ;
    }
}

void Config::readConfigFile()
{
    char *pLine = nullptr;
    size_t len = 0;
    ssize_t nread;
    while ((nread = getline(&pLine, &len, m_pFp)) != -1) {
        //移除多余的空格等符号
        char *p = strchr(pLine, ':');

        if (p == nullptr) return;

        char *pValue = removeSpace(p, strlen(p));
        char *pKey = removeSpace(pLine, strlen(pLine) - strlen(p) - 1);
        //printf("%s, %s\n", pKey, pValue);
        m_mapKeyValue.insert(std::make_pair(pKey, pValue));
    }
}

void Config::writeConfigFile()
{

}

void Config::closeConfigFile() {
    if (m_pFp != nullptr) {
        fclose(m_pFp);
    }
}

char *Config::removeSpace(char *strChar, size_t length) {
    char *pStart = strChar;
    char *pEnd = strChar + length;

    while ((*pStart == ' ') || (*pStart == ':')) {
        pStart++;
    }

    while ((*pEnd == ' ') || (*pEnd == '\n') || (*pEnd == '\0')) {
        pEnd--;
    }
    *(++pEnd) = '\0';
    return pStart;
}

void Config::setValue(const std::string &strKey, const std::string &strValue) {
    m_mapKeyValue.insert(std::make_pair(strKey, strValue));
}

const char *Config::getValue(std::string strKey) const {
    for (auto mapKeyValue : m_mapKeyValue) {
        //printf("%s: %s\n", mapKeyValue.first.c_str(), mapKeyValue.second.c_str());
        if (mapKeyValue.first == strKey) {
            return mapKeyValue.second.c_str();
        }
    }
    return "";
}